﻿/*****************************************************************
 *Yuga Technology
 *@author YUga studio
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webbase.modules.invoicing.web;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.oplink.webbase.common.persistence.Page;
import com.oplink.webbase.modules.invoicing.entity.Stock;
import com.oplink.webbase.modules.invoicing.entity.SubStock;
import com.oplink.webbase.modules.invoicing.service.StockService;
import com.oplink.webbase.modules.invoicing.service.SubStockService;
import com.oplink.webbase.modules.sys.entity.User;
import com.oplink.webbase.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webbase.modules.sys.web.BaseController;

/**
 * Stock管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /queue/
 * Create pushlet : GET /queue/pushlet
 * Create page : GET /queue/create
 * Create action : POST /queue/create
 * Update page : GET /queue/update/{id}
 * Update action : POST /queue/update
 * Delete action : GET /queue/delete/{id}
 * 告警Controller
 * 
 * @author YUga studio
 * @version 2015-01-12
 */
@Controller
@RequestMapping(value = "invoicing/stock")
public class StockController extends BaseController {

	@Autowired
	private StockService stockService;

	@Autowired
	private SubStockService subStockService;

	@RequiresPermissions("modules/invoicing:stock:view")
	@RequestMapping(value = { "list", "" }, method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Stock stock, HttpServletRequest request, HttpServletResponse response, Model model) {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long userId = getCurrentUserId();

		Page<Stock> pages = stockService.find(new Page<Stock>(request, response), stock);
		// Page<Stock> pages = stockService.getUserStock(userId, searchParams, pageNumber, pageSize, sortType);
		model.addAttribute("pages", pages);
		model.addAttribute("userId", userId);

		// 将搜索条件编码成字符串，用于排序，分页的URL
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "modules/invoicing/stockList";
	}

	@RequiresPermissions("modules/invoicing:stock:edit")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Stock updateForm(@PathVariable("id") Long id) {
		Stock stock = stockService.getStock(id);
		stock.setUser(null);
		return stock;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("stock") Stock stock, RedirectAttributes redirectAttributes) {
		try {
			User user = new User(getCurrentUserId());
			stock.setUser(user);
			stockService.saveStock(stock);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

	@RequiresPermissions("modules/invoicing:stock:view")
	@RequestMapping(value = "form")
	public String form(Stock stock, Model model) {
		model.addAttribute("stock", stock);
		return "modules/invoicing/stockForm";
	}

	@RequiresPermissions("modules/invoicing:stock:edit")
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("userId", getCurrentUserId());
		model.addAttribute("action", "create");
		return "modules/invoicing/stock/create";
	}

	@RequestMapping(value = "subStock/{goodsId}", method = RequestMethod.GET)
	@ResponseBody
	public SubStock subStock(@PathVariable("goodsId") String goodsId) {
		return stockService.getSubStock(goodsId);
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(HttpServletRequest req, RedirectAttributes redirectAttributes, Model model) {
		try {

			// Check the specify good exist.
			String gid = req.getParameter("goodsId");
			if ((gid != null) && !stockService.isExistGoods(gid)) {
				Stock stock = new Stock();
				stock.setStockFormId(req.getParameter("stockFormId"));
				stock.setStockTime(req.getParameter("stockTime"));
				stock.setOperatman(getCurrentUserId());

				SubStock subStock = new SubStock();
				subStock.setStockFormId(req.getParameter("stockFormId"));
				subStock.setGoodsId(req.getParameter("goodsId"));
				subStock.setCostPrice(req.getParameter("costPrice"));
				subStock.setSalePrice(req.getParameter("salePrice"));
				subStock.setGoodsState(req.getParameter("goodsState"));
				subStock.setStockQuantity(Integer.parseInt(req.getParameter("stockQuantity")));
				subStock.setMinReserves(Integer.parseInt(req.getParameter("minReserves")));
				subStock.setNorReserves(Integer.parseInt(req.getParameter("norReserves")));
				subStock.setMaxReserves(Integer.parseInt(req.getParameter("maxReserves")));
				subStock.setRecentOperDate(new Date());
				User user = new User(getCurrentUserId());
				stock.setUser(user);
				subStock.setUser(user);
				model.addAttribute("stock", stock);
				stockService.saveStock(stock);
				subStockService.saveSubStock(subStock);

				redirectAttributes.addFlashAttribute("message", "创建任务成功");
			}
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					stockService.deleteStock(Long.valueOf(idItem));
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			return "0";
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
